package com.ttn.business.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ttn.business.service.ProductService;
import com.ttn.common.core.entity.Result;
import com.ttn.common.core.entity.business.Product;
import com.ttn.common.core.entity.business.bo.ModifyProductSortBO;
import com.ttn.common.core.entity.business.query.ProductQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * (product)表控制层
 *
 * @author xxxxx
 */
@RestController
@Slf4j
@RequestMapping("/product")
public class ProductController {
    /**
     * 服务对象
     */
    @Resource
    private ProductService productService;

    /**
     * 保存产品
     *
     * @param request
     * @param product
     * @return
     */
    @PostMapping("/save/product")
    public Result saveProduct(HttpServletRequest request, @RequestBody Product product) {
        log.info("ProductController saveProduct ,参数:{}", product);
        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper();
        productLambdaQueryWrapper.eq(Product::getProductName, product.getProductName());
        //判断等级名称是否重复。不重重则直接保存
        if (productService.count(productLambdaQueryWrapper) > 0) {
            return Result.fail("产品名名称重复,请确认后重试");
        }
        product.setSort(Math.toIntExact(productService.count() + 1));
        productService.save(product);
        return Result.success();
    }

    /**
     * 修改产品
     *
     * @param request
     * @param product
     * @return
     */
    @PutMapping("/modify/product")
    public Result modifyProduct(HttpServletRequest request, @RequestBody Product product) {
        log.info("ProductController saveProduct ,参数:{}", product);
        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productLambdaQueryWrapper.eq(Product::getProductName, product.getProductName());
        productLambdaQueryWrapper.ne(Product::getId, product.getId());
        //判断等级名称是否重复。不重重则直接保存
        if (productService.count(productLambdaQueryWrapper) > 0) {
            return Result.fail("产品名名称重复,请确认后重试");
        }
        productService.updateById(product);
        return Result.success();
    }

    /**
     * 分页查询产品
     *
     * @param request
     * @param productQuery
     * @return
     */
    @PostMapping("/query/product-page")
    public Result queryProductPage(HttpServletRequest request,
                                   @RequestBody ProductQuery productQuery) {
        log.info("ProductController queryProductPage ,productQuery:{}", productQuery);
        IPage<Product> productIPage = new Page<>(productQuery.getPageNum(), productQuery.getPageSize());
        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productLambdaQueryWrapper.eq(StrUtil.isNotBlank(productQuery.getProductName()), Product::getProductName,
                productQuery.getProductName());
        productLambdaQueryWrapper.eq(StrUtil.isNotBlank(productQuery.getProductNumber()), Product::getProductNumber,
                productQuery.getProductNumber());
        productLambdaQueryWrapper.orderByAsc(Product::getSort);
        return Result.success(productService.page(productIPage, productLambdaQueryWrapper));
    }

    /**
     * 删除商品
     *
     * @param request
     * @param id
     * @return
     */

    @DeleteMapping("/delete/product-by-id/{id}")
    public Result deleteProductById(HttpServletRequest request, @PathVariable("id") Integer id) {
        log.info("ProductController deleteProductById ,参数id:{}", id);
        productService.removeById(id);
        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper();
        productLambdaQueryWrapper.ne(Product::getId, id);
        productLambdaQueryWrapper.orderByAsc(Product::getSort);
        List<Product> productList = productService.list(productLambdaQueryWrapper);
        if (productList.size() > 0) {
            AtomicInteger i = new AtomicInteger(1);
            productList.stream().forEach(courseUnit1 -> {
                courseUnit1.setSort(i.getAndIncrement());
            });
            productService.updateBatchById(productList);
        }
        return Result.success();
    }

    /**
     * 修改产品排序
     *
     * @param request
     * @param modifyProductSortBO
     * @return
     */
    @PutMapping("/modify/course-unit-vocabulary-sort")
    public Result modifyProductSort(HttpServletRequest request, @RequestBody ModifyProductSortBO modifyProductSortBO) {
        log.info("ProductController modifyCourseUnitSort ,参数:{}", modifyProductSortBO);
        Product product = productService.getById(modifyProductSortBO.getId());
        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper();
        productLambdaQueryWrapper.ne(Product::getId, modifyProductSortBO.getId());
//        courseUnitLambdaQueryWrapper.eq(Product::getGrade, product.getGrade());
        productLambdaQueryWrapper.orderByAsc(Product::getSort);
        List<Product> productList = productService.list(productLambdaQueryWrapper);
        if (productList.size() > 0) {
            int sortIndex = 0;
            if (modifyProductSortBO.getSortingBehavior().equals(-1)) {
                if (product.getSort() - 2 > 0) {
                    sortIndex = product.getSort() - 2;
                }
            } else if (modifyProductSortBO.getSortingBehavior().equals(1)) {
                sortIndex = product.getSort();
            }
            productList.add(sortIndex, product);
            AtomicInteger i = new AtomicInteger(1);
            productList.stream().forEach(courseUnit1 -> {
                courseUnit1.setSort(i.getAndIncrement());
            });
            productService.updateBatchById(productList);
        }
        return Result.success();
    }


}
